import time

from selenium.webdriver import Chrome
# 【2】驱动位置服务
from selenium.webdriver.chrome.service import Service
# 【3】选择器
from selenium.webdriver.common.by import By

# 【二】创建浏览器对象
# 【1】指定驱动位置
executable_path = "./chromedriver.exe"
service = Service(
    executable_path=executable_path
)
# 【2】创建浏览器对象
browser = Chrome(
    service=service
)

# 【三】打开目标网址
browser.get("https://www.jd.com/")
time.sleep(3)

# 【四】执行JS代码
# 【1】滚动到页面底部
'''
js_str = "window.scrollTo(0,document.body.scrollHeight)"
browser.execute_script(js_str)
'''
# 【2】通过JS替换文本内容
'''
search_kw = browser.find_element(By.XPATH, '//*[@id="key"]')
# search_btn.click()
js_str = 'arguments[0].value=arguments[1]'
browser.execute_script(js_str, search_kw, "hello kitty")
'''
# 【3】点击按钮
'''
search_kw = browser.find_element(By.XPATH, '//*[@id="key"]')
js_str = 'arguments[0].value=arguments[1]'
browser.execute_script(js_str, search_kw, "hello kitty")
js_str = 'arguments[0].click()'
search_btn = browser.find_element(By.XPATH, '//*[@id="search"]/div/div[2]/button')
browser.execute_script(js_str, search_btn)
time.sleep(3)
'''
# 【4】拖拽标签元素
"""
# 使用JavaScript拖动一个可拖动的元素到目标位置
source_element = browser.find_element(By.ID,'source_element_id')
target_element = browser.find_element(By.ID,'target_element_id')
browser.execute_script('''
    var source = arguments[0], target = arguments[1];
    var offsetX = target.getBoundingClientRect().left - source.getBoundingClientRect().left;
    var offsetY = target.getBoundingClientRect().top - source.getBoundingClientRect().top;
    var event = new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window });
    source.dispatchEvent(event);
    event = new MouseEvent('mousemove', { bubbles: true, cancelable: true, view: window, clientX: offsetX, clientY: offsetY });
    source.dispatchEvent(event);
    event = new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window });
    source.dispatchEvent(event);
''', source_element, target_element)
"""
# 【5】获取标签属性
'''
# 使用JavaScript获取元素的属性值
element = browser.find_element(By.ID,'element_id')
attribute_value = browser.execute_script('return arguments[0].getAttribute("attribute_name");', element)
print(attribute_value)
'''
